package main

import (
	"fmt"
	"github.com/bitly/go-simplejson"
	"io"
	"net/http"
	"os"
	"os/exec"
	"runtime"
	"time"
)

var notify_api = "https://portal-service.nwpu.edu.cn/v1/cms/content/getColumncontents?kw=&columnId=8aaa851e7618996801761d1b7d310006&pageNo=1&pageSize=1"
var content_api = "https://portal-service.nwpu.edu.cn/v1/cms/content/getOne?id="
var last_update_time = "2000-01-01 00:00:00"
var tmp_file = ""

func main() {
	switch runtime.GOOS {
	case "windows":
		{
			tmp_file = os.Getenv("temp") + "\\"
		}
	case "linux":
		{
			tmp_file = "/tmp/"
		}
	}
	tmp_file += "nwpu_notify.html"
	for {
		get, _ := http.Get(notify_api)
		all, _ := io.ReadAll(get.Body)
		get.Body.Close()
		json, _ := simplejson.NewJson(all)
		latest_notification := json.Get("data").Get("allContents").GetIndex(0)
		update_time := latest_notification.Get("releaseStartTime").MustString()
		id := latest_notification.Get("id").MustString()
		title := latest_notification.Get("title").MustString()
		releaseDeptName := latest_notification.Get("releaseDeptName").MustString()
		if update_time > last_update_time {
			last_update_time = update_time
			resp, _ := http.Get(content_api + id)
			readAll, _ := io.ReadAll(resp.Body)
			resp.Body.Close()
			json, _ := simplejson.NewJson(readAll)
			content := json.Get("data").Get("content").Get("content").MustString()
			file, _ := os.OpenFile(tmp_file, os.O_RDWR|os.O_CREATE, 0755)
			file.Truncate(0)
			file.Seek(0, 0)
			file.WriteString(fmt.Sprintf("<h1>%s</h1><h2>%s</h2>", title, releaseDeptName))
			file.WriteString(content)
			file.WriteString("<p><a href='https://ecampus.nwpu.edu.cn/main.html#/newsDetail?id=" + id + "'>阅读原文</a></p>")
			file.Close()
			switch runtime.GOOS {
			case "windows":
				exec.Command(`cmd`, `/c`, `start`, tmp_file).Start()
			case "linux":
				exec.Command(`xdg-open`, tmp_file).Start()
			case "mac":
				exec.Command(`open`, tmp_file).Start()
			}
		}
		time.Sleep(time.Minute * 10)
	}
}
